package com.xyc.servlet.list;

import com.xyc.mapper.SongListMapper;
import com.xyc.mapper.SongMapper;
import com.xyc.pojo.Song;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@WebServlet("/addNewListReal")
public class AddNewListReal extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //获取数据添加页面上的内容 尤其是复选框中的选中歌曲  数据添加  返回上一级
        req.setCharacterEncoding("utf-8");
        String[] music = req.getParameterValues("music");
        String list_name = req.getParameter("list_name");
        String list_memo = req.getParameter("list_memo");

        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-dao.xml");
        SongListMapper mapper = ctx.getBean("songListMapper", SongListMapper.class);
        SongMapper songMapper = ctx.getBean("songMapper", SongMapper.class);
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        Map map = new HashMap();
        map.put("name", list_name);
        map.put("uuid", uuid);
        map.put("content", "");
        map.put("memo", list_memo);

        mapper.addSongList(map); // 歌单添加成功，但是要将对应的歌曲 list属性设置

        List<Song> songList_1203 = songMapper.selectSong();

        Map map2 = new HashMap();

        for (int j = 0; j < music.length; j++) { // music[0] = 4  music[1] = 5
            for (int i = 0; i < songList_1203.size(); i++) {
                Song song = songList_1203.get(i);
                if (Integer.parseInt(music[j]) == i) {
                    map2.put("list", uuid);
                    map2.put("Song_id", song.getSong_id());
                    songMapper.updateLast(map2);
                }
            }
        }

        req.getRequestDispatcher("/myList").forward(req, resp);
    }
}
